<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Lock, Shop, Location, Document } from '@element-plus/icons-vue'
import { merchantLoginService, merchantRegisterService } from '../../api/merchant'
import { useMerchantStore } from '../../stores/merchant'
import { useUserStore } from '../../stores/user'

const router = useRouter()
const merchantStore = useMerchantStore()
const userStore = useUserStore()

// 控制登录/注册切换
const isLogin = ref(true)

// 登录表单数据
const loginForm = reactive({
  name: '',
  password: ''
})

// 注册表单数据
const registerForm = reactive({
  name: '',
  password: '',
  confirmPassword: '',
  logo: '',
  description: '',
  province: '',
  city: '',
  district: '',
  detail: ''
})

// 表单引用
const loginFormRef = ref()
const registerFormRef = ref()

// 登录表单验证规则
const loginRules = {
  name: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { min: 1, max: 16, message: '店铺名称长度为1-16个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度为5-16个字符', trigger: 'blur' }
  ]
}

// 注册表单验证规则
const registerRules = {
  name: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { min: 1, max: 16, message: '店铺名称长度为1-16个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '密码长度为5-16个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: any, callback: any) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  description: [
    { required: true, message: '请输入店铺描述', trigger: 'blur' }
  ],
  province: [
    { required: true, message: '请输入省份', trigger: 'blur' }
  ],
  city: [
    { required: true, message: '请输入城市', trigger: 'blur' }
  ],
  district: [
    { required: true, message: '请输入区/县', trigger: 'blur' }
  ],
  detail: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 登录处理
const handleLogin = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录用户账号')
    router.push('/login')
    return
  }

  try {
    await loginFormRef.value.validate()
    const userId = Number(userStore.userId)
    const res: any = await merchantLoginService(loginForm.name, loginForm.password, userId)
    
    if (res.code === 0) {
      // 保存商家token
      merchantStore.setMerchantToken(res.data)
      ElMessage.success('登录成功')
      // 跳转到店铺主页
      router.push('/merchant/dashboard')
    } else {
      ElMessage.error(res.message || '登录失败')
    }
  } catch (error: any) {
    console.error('登录失败:', error)
    if (error !== false) {
      ElMessage.error('登录失败，请检查输入')
    }
  }
}

// 注册处理
const handleRegister = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录用户账号')
    router.push('/login')
    return
  }

  try {
    await registerFormRef.value.validate()
    const userId = Number(userStore.userId)
    
    const merchantData = {
      name: registerForm.name,
      password: registerForm.password,
      logo: registerForm.logo || '',
      description: registerForm.description,
      province: registerForm.province,
      city: registerForm.city,
      district: registerForm.district,
      detail: registerForm.detail
    }
    
    const res: any = await merchantRegisterService(merchantData, userId)
    
    if (res.code === 0) {
      ElMessage.success('注册成功，请登录')
      // 切换到登录页面
      isLogin.value = true
      // 自动填充店铺名称
      loginForm.name = registerForm.name
    } else {
      ElMessage.error(res.message || '注册失败')
    }
  } catch (error: any) {
    console.error('注册失败:', error)
    if (error !== false) {
      ElMessage.error('注册失败，请检查输入')
    }
  }
}

// 切换登录/注册
const toggleMode = () => {
  isLogin.value = !isLogin.value
}
</script>

<template>
  <div class="merchant-auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <el-icon class="shop-icon"><Shop /></el-icon>
        <h2>{{ isLogin ? '商家登录' : '商家注册' }}</h2>
      </div>

      <!-- 登录表单 -->
      <el-form
        v-if="isLogin"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="auth-form"
      >
        <el-form-item prop="name">
          <el-input
            v-model="loginForm.name"
            placeholder="店铺名称"
            :prefix-icon="Shop"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        <el-button type="primary" size="large" class="submit-btn" @click="handleLogin">
          登录
        </el-button>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-else
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="auth-form"
      >
        <el-form-item prop="name">
          <el-input
            v-model="registerForm.name"
            placeholder="店铺名称"
            :prefix-icon="Shop"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="确认密码"
            :prefix-icon="Lock"
            size="large"
            show-password
          />
        </el-form-item>
        <el-form-item prop="description">
          <el-input
            v-model="registerForm.description"
            type="textarea"
            placeholder="店铺描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item prop="province">
          <el-input
            v-model="registerForm.province"
            placeholder="省份"
            :prefix-icon="Location"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="city">
          <el-input
            v-model="registerForm.city"
            placeholder="城市"
            :prefix-icon="Location"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="district">
          <el-input
            v-model="registerForm.district"
            placeholder="区/县"
            :prefix-icon="Location"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="detail">
          <el-input
            v-model="registerForm.detail"
            placeholder="详细地址"
            :prefix-icon="Document"
            size="large"
          />
        </el-form-item>
        <el-button type="primary" size="large" class="submit-btn" @click="handleRegister">
          注册
        </el-button>
      </el-form>

      <!-- 切换按钮 -->
      <div class="toggle-mode">
        <span v-if="isLogin">还没有店铺？</span>
        <span v-else>已有店铺？</span>
        <a href="#" @click.prevent="toggleMode">
          {{ isLogin ? '立即注册' : '立即登录' }}
        </a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.merchant-auth-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 2rem;
}

.auth-card {
  background: white;
  border-radius: 1rem;
  padding: 2.5rem;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
}

.auth-header {
  text-align: center;
  margin-bottom: 2rem;

  .shop-icon {
    font-size: 3rem;
    color: #667eea;
    margin-bottom: 1rem;
  }

  h2 {
    font-size: 1.75rem;
    color: #333;
    margin: 0;
  }
}

.auth-form {
  .submit-btn {
    width: 100%;
    margin-top: 1rem;
  }
}

.toggle-mode {
  text-align: center;
  margin-top: 1.5rem;
  color: #666;

  a {
    color: #667eea;
    text-decoration: none;
    margin-left: 0.5rem;
    font-weight: 500;

    &:hover {
      text-decoration: underline;
    }
  }
}

:deep(.el-input__wrapper) {
  padding: 0.75rem 1rem;
}

:deep(.el-textarea__inner) {
  padding: 0.75rem 1rem;
}
</style>
